const env = require('./config.js');
const Base64 = require('./Base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

const uploadFile = function(params, dir, successc, failc) {
	console.log(params);
	if (!params.tempFilePath || params.tempFilePath.length < 9) {
		wx.showModal({
			title: '文件错误',
			content: '请重试',
			showCancel: false,
        });
        return;
	}
	const path = params.tempFilePath.replace('wxfile://', '');
	const aliyunFileKey = dir + path.replace('http://tmp/', ''); //'wxfile://' 'http://tmp/'
	const aliyunServerURL = env.uploadImageUrl;
	const accessid = env.OSSAccessKeyId;
	const policyBase64 = getPolicyBase64();
	const signature = getSignature(policyBase64);

	console.log('aliyunFileKey=', aliyunFileKey);
  console.log('aliyunServerURL', aliyunServerURL);
  
	const uploadTask = wx.uploadFile({
		url: aliyunServerURL,
		filePath: params.tempFilePath,
		name: 'file',
		formData: {
			'key': aliyunFileKey,
			'policy': policyBase64,
			'OSSAccessKeyId': accessid,
			'signature': signature,
			'success_action_status': '200',
		},
		success: function(res) {
			console.log(res);
			if (res.statusCode != 200) {
				if (params.fail) {
					params.fail(res)
				}
				return;
			}
			successc(aliyunServerURL + "/" + aliyunFileKey);
			if (params.success) {
				params.success(aliyunFileKey);
			}
		},
		fail: function(err) {
			err.wxaddinfo = aliyunServerURL;
			failc(err);
		},
  })
  uploadTask.onProgressUpdate((res) => { 
    //console.log('上传进度', res.progress) 
    //console.log('已经上传的数据长度', res.totalBytesSent) 
    //console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend) 
    wx.showLoading({
      title: '上传中' + res.progress + '%',
    })
  }) 
}


const getPolicyBase64 = function() {
	let date = new Date();
	date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		"expiration": srcT,
		//设置该Policy的失效时间
		"conditions": [["content-length-range", 0, 1024 * 1024 * 1024] // 设置上传文件的大小限制,1G
		]
	};
	const policyBase64 = Base64.encode(JSON.stringify(policyText));
	return policyBase64;
}

const getSignature = function(policyBase64) {
	const accesskey = env.AccessKeySecret;
	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true
	});
	const signature = Crypto.util.bytesToBase64(bytes);
	return signature;
}

module.exports = uploadFile;